package org.swift.commons.util.io;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

public class FileUtils {
	/**
	 * Creates parent directory(-ies) of input File if they do not 
	 * exist.
	 */
	public static boolean checkPaths(File currentFile) throws IOException
	{
		if(currentFile == null)
		{
			return false;
		}
		if(currentFile.exists())
		{
			return true;
		}
		if(checkPaths(currentFile.getCanonicalFile().getParentFile()))
		{
			currentFile.mkdirs();
			return true;
		}
		else
		{
			return false;
		}
	}
	
	/**
	 * Creates a new directory in the parentDirectory using a randomUUID as the name
	 * 
	 * @param parentDirectory
	 * @return
	 * @throws IOException
	 */
	public static File createTempDirectory(File parentDirectory) throws IOException {
		int attemptCount = 0;
		File newTempDir;
		do {
			attemptCount++;
			if (attemptCount > 20) {
				throw new IOException(
						"The highly improbable has occurred! Failed to "
								+ "create a unique temporary directory after 20 attempts.");
			}
			String dirName = UUID.randomUUID().toString();
			newTempDir = new File(parentDirectory, dirName);
			newTempDir.mkdirs();			
		} while (!newTempDir.exists());
		return newTempDir;
	}

	public static File findFile(String filename, File directory) {
		try {
			File[] content = directory.listFiles(); // content now contains an  array of files/folders
			for (int i = 0; i < content.length; i++) {
				File file = content[i];
				if (file.isDirectory()){
					File retFile = findFile(filename,file);
					if(retFile!=null){
						return retFile;
					}
				}else if(file.getName().equals(filename)){
					return file;
				}
			}
		} catch (Exception e) {
			e.printStackTrace(); // and why
		}
		return null;
	}
	
}
